package com.lollipop.synthential.gps;

import com.drew.imaging.FileType;
import com.drew.imaging.FileTypeDetector;
import com.drew.imaging.jpeg.JpegMetadataReader;
import com.drew.imaging.png.PngMetadataReader;
import com.drew.lang.GeoLocation;
import com.drew.metadata.Metadata;
import com.drew.metadata.exif.GpsDirectory;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Objects;
import java.util.Scanner;

/**
 * @Author: J.K
 * @Date: 2021-07-29 13:42
 * @Description: 获取图片GPS信息的demo
 */
public class PhotoGps {
    public static void main(String[] args) {
        System.out.println("请输入图片路径：");
        Scanner scanner = new Scanner(System.in);
        String path = scanner.nextLine();
        getGpsDirectory(path);
    }

    /**
     * 获取文件
     *
     * @param filePath 文件路径
     */
    private static void getGpsDirectory(String filePath) {
        File picFile = new File(filePath);
        getGpsDirectory(picFile);
    }

    /**
     * 获取GPS信息
     *
     * @param picFile
     */
    private static void getGpsDirectory(File picFile) {
        Metadata picFileMetadata = getPicFileMetadata(picFile);
        GpsDirectory gpsDirectory = picFileMetadata.getFirstDirectoryOfType(GpsDirectory.class);
        if (Objects.nonNull(gpsDirectory)) {
            GeoLocation geoLocation = gpsDirectory.getGeoLocation();
            System.out.println(geoLocation.getLongitude());
            System.out.println(geoLocation.getLatitude());
        }
    }

    /**
     * 获取元数据
     *
     * @param picFile
     * @return
     */
    private static Metadata getPicFileMetadata(File picFile) {
        Metadata metadata = null;
        try (InputStream inputStream = new FileInputStream(picFile);
             BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream)) {
            FileType fileType = FileTypeDetector.detectFileType(bufferedInputStream);

            switch (fileType) {
                case Png:
                    metadata = PngMetadataReader.readMetadata(picFile);
                    break;
                case Jpeg:
                    metadata = JpegMetadataReader.readMetadata(picFile);
                    break;
                default:
                    return metadata;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return metadata;
    }
}
